function hb = hrfboost(hd)
% hrfboost  - assume that best fit is the (root of) sum of squares
%
% FORMAT:       hb = hrfboost(hd)
%
% Input fields:
%
%       hd          HRF with derivates (as last non-singleton dimension)
%
% Output fields:
%
%       hb          boosted HRF estimate

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin ~= 1 || ...
   ~isnumeric(hd)
    error( ...
        'BVQXtools:BadArgument', ...
        'Bad or missing argument.' ...
    );
end

% get size and dimensions
sz = size(hd);
nd = ndims(hd);

% special case for empty input
if isempty(hd)
    if nd == 2 && ...
       (sz(2) == 1 || ...
        sz(2) == 0)
        sz = [0, 0];
    else
        sz(end) = 1;
    end
    hb = reshape(hd, sz);
    return;
end

% for 2-dim data check if sz(2) == 1
if nd == 2 && ...
    sz(2) == 1
    hb = sign(hd(1)) * sqrt(sum(hd .* hd));
    return;
end

% otherwise operate along last dim
if nd == 2
    ts = [sz(1), 1];
else
    ts = sz(1:end-1);
end
hd = reshape(hd, [prod(ts), sz(end)]);
hb = reshape(sign(hd(:, 1)) .* sqrt(sum(hd .* hd, 2)), ts);
